
var _Ppt = function () {


  let genPpt = (type,id,data)=>{
    $$.fetch("ppt",id,(ppt)=>{
      let pg = new PptGen({});
      pg.genPpt(ppt,data);
    })
  };
  return {
    genPpt
  }
}();

function PptGen(setting) {
  this.ppt = null;
  let _this = this;
  this.pptx = null;
  this.data = null;
  this.setting = setting||{};
  this.settingData = {};
  this.masterItemsMap = {};
  let genMaster = ()=>{
    $.each(_this.ppt.masters,(i,master)=>{
      _this.masterItemsMap[master["name"]] = master["items"];
      _this.pptx.defineSlideMaster({
        title: master.name,
        objects: [{
          image: {
            x: 0,
            y: 0,
            w: '100%',
            h: '100%',
            path: master.pic
          }
        },
          // {image: { x:0, y:0, w:cm(16.79), h:cm(2.13), align:"right", data: imageList["logo"]}},
        ],
      });
    })
  };

  let genPageByResource = (resourceJob)=>{
    // 遍历需要通过数据生成的页面
    $.each(resourceJob,(resource,pages)=>{
      delete resourceJob[resource];
      if(! pages){
        return ;
      }
      //找对应的数据源设置
       let find = _this.ppt["resources"].find(item=>item.id==resource);
       //遍历所有有数据项
       $.each(find.certTypeIds,(k,ctId)=>{
        
         // 找到对应的数据list
         let findData  = _this.data.find(d=> d.certTypeId == ctId);
         if(findData){
           // 遍历页面
           $.each(pages,(i3,page)=>{
             genPageByData(page,findData,find);
           })
         }
       })
    });
  };
  let genPageByData = (page,data,options)=>{
    // 奖项数据
    if(page.type == 2){
      genSinglePage(page,data);
    }else{
      let list = data["Certs"];
      let doByPageSize = (pData,tempList)=>{
        let group = tempList.groupByNum(options.pageSize);
        $.each(group,(i1,items)=>{
          genSinglePage(page,pData,items);
        });
      }
      if (options.sortBy){
        list = list.sortBy(val(options.sortBy));
      }
      if (options.groupBy){
        let gs = list.groupBy(val(options.groupBy));
        $.each(gs,(i0,g)=>{
          let pData = $.extend({},data,g["key"]);
          if (options.pageSize) {
            doByPageSize(pData, g["items"]);
          }else{
            genSinglePage(page,data,g["items"]);
          }
        })
      }
      else if (options.pageSize){
        doByPageSize(data,list)
      }else{
        genSinglePage(page,data,list);
      }
    }
  };
  let isItemsData =(texts)=>{
    for(let i=0;i< (texts||[]).length;i++){
      if (texts[i]["text"].indexOf("{items.") >=0){
        return true;
      }
    }
    return false;
  };
  let joinData = (data,itemData)=>{
    let result = $.extend({},data);
    $.each(itemData,(k,v)=>{
      result["items."+k] = v
    })
    return result;
  };

  let getFormatTexts = (texts, itemData)=>{
    itemData = $.extend({},this.settingData,itemData);
    let newTexts = [];
    $.each(texts,(i3,textData)=>{
      let text = textData["text"];
      // {Division-{Division}} 需要转两次的情况.所以用了两次format
      let textContent = text.format(itemData);
      textContent = textContent.format(itemData);
      // 新增加的带"|"的处理.
      let ts = (textContent+"").split("｜");
      (ts||[]).forEach(t => newTexts.push($.extend({},textData,{text:t})));
    });
    return newTexts;
  }

  let getTexts = (texts,data,items) =>{
    let newTexts = [];
    if (items && isItemsData(texts)){
      $.each(items,(i3,v3)=>{
        let itemData = joinData(data,v3);
        newTexts.push(...getFormatTexts(texts, itemData));
      });
    }else{
      newTexts.push(...getFormatTexts(texts, data));
    }
    return newTexts;
  };
  function getRows2(texts,groups,data,items){
   
    let group = items.groupByNums(groups);
    let rows = [];
    $.each(group,(k,gItems)=>{
      let rowTexts = getTexts(texts,data,gItems);
      rows.push({"text":rowTexts});
    });
    return [rows];
  }
  function getRows(texts,groups=[],data,items=[]){
    let rows = [];
    let i=0;
    for(let col=0;col < groups.length;col++){
      let row = 0;
      let maxRow = parseInt(groups[col]);
      while(row < maxRow){
        if(!rows[row]){
          rows[row]=[];
        }
        if( i < items.length){
          let rowTexts = getTexts(texts,data,[items[i]]);
          rows[row].push({text:rowTexts});
          i++;
        }else{
          rows[row].push({text:" "});
        }
        row++;
      }
      if( i >= items.length){
        break;
      }
    }

    return rows;
  }


  function genSinglePage(page,data,items){
    let side = _this.pptx.addSlide(page.master);
    $.each(page.items,(i2,item)=>{
      if (item.options.conf){
        try{
          let conf = (item.options.conf).format(data);
          conf = conf.format(data);
          if (!eval(conf)){
            return;
          }
        }catch (e){
          console.error("text条件判断出现异常",item,e);
        }

      }

      let itemOptions = $.extend({},_this.ppt.default,item.options);
     
      if (item.options.groups) {
        try{
          let groups = JSON.parse(item.options.groups);
          let rows = getRows(item.texts,groups,data,items);
          itemOptions["border"] = {type:'none'};
          side.addTable(rows, itemOptions)
        }catch (e) {
        
        }
        
      }else{
        let newTexts = getTexts(item.texts,data,items);
        side.addText(newTexts,itemOptions)
      }
    });
  }
  let genPage = ()=>{
    let resourceJob = {};
    $.each(_this.ppt.pages, (i,page)=>{
      if(page.isHidden){
        return;
      }
      formatPageOptions(page);
      if(page.resource){
        if (resourceJob[page.resource]){
          resourceJob[page.resource].push(page);
        }else{
          genPageByResource(resourceJob);
          resourceJob[page.resource] = [page];
        }
        return
      }
      genPageByResource(resourceJob);
      genSinglePage(page,_this.setting)
    });
    genPageByResource(resourceJob);
  };
  function formatPageOptions(page){
    let items = page.items;
    if (page["master"]){
      let masterItems = JSON.parse(JSON.stringify(_this.masterItemsMap[page["master"]] || []));
      items.push(...masterItems);
    }

    $.each(items,(i2,item)=> {
      let itemOptions = item.options;
      itemOptions.x = cm(itemOptions.x || 0);
      itemOptions.y = cm(itemOptions.y || 0);
      if (isRealNum(itemOptions.w)) {
        itemOptions.w = cm(itemOptions.w);
      }
      if (isRealNum(itemOptions.h)) {
        itemOptions.h = cm(itemOptions.h);
      }
      if (isRealNum(itemOptions.inset)) {
        itemOptions.inset = cm(itemOptions.inset);
      } else if (itemOptions.inset) {
        try {
          itemOptions.inset = JSON.parse(itemOptions.inset);
          $.each(itemOptions.inset, (kk, vv) => itemOptions.inset[kk] = round(cm2pt(vv),1))
        } catch (e) {}
      }
      if (itemOptions.groups) {
        try {
          itemOptions["margin"] = itemOptions["inset"];
        } catch (e) {}
      }
      if(itemOptions["align"] ===""){
        delete itemOptions["align"]
      }
      $.each(item.texts,(i3,text)=>{
        if(isRealNum(text.options["lineSpacing"])){
          text.options["lineSpacing"] = round(text.options["lineSpacing"],0)
        }else{
          delete text.options["lineSpacing"]
        }
      })
    })
  }
  let cm = (num)=>{ return num / 2.54;};
  let cm2pt = (num)=> round(num*72/2.54,2);
  this.genPpt = (ppt,data)=>{
    _this.ppt = ppt;
    if (ppt.unit == "inches"){
      cm = (num)=>{return num;}
    }else if (ppt.unit == "pt"){
      cm = (num)=>{ return num / 72;};
    }
    let pptx = new PptxGenJS();
  
    pptx.defineLayout({
      name: 'ppt',
      width: cm(ppt.width),
      height: cm(ppt.height)
    });
    pptx.layout = 'ppt';
    _this.pptx = pptx;
    _this.data = data;
    genMaster();
    genPage();
    pptx.write("blob").then(data =>{
      upload("/upload",{
        "name":ppt.name+"."+(new Date()).Format("yyyyMMddhhmmss")+".pptx", data
      },(r)=>{
        layer.msg("成功下载，路径："+r["data"])
      },(r)=>{
        layer.msg("下载失败")
      })
    })
    
  }
}